﻿using LJX.SmartPark.Common.ResponseOutput;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net;
using System.Text;

namespace LJX.SmartPark.WebApi.Filters
{
    public class SmartParkServerExpectionFilter : IExceptionFilter
    {
        private readonly ILogger<SmartParkServerExpectionFilter> _logger;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        public SmartParkServerExpectionFilter(ILogger<SmartParkServerExpectionFilter> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                StringBuilder stringBuilder = new StringBuilder();
                string expectionMessage = context.Exception.InnerException != null
                    ? context.Exception.InnerException.Message : context.Exception.Message;

                var description = context.ActionDescriptor;

                if (!string.IsNullOrEmpty(description.DisplayName))
                {
                    stringBuilder.Append(description.DisplayName);
                }

                stringBuilder.AppendLine(expectionMessage);
                _logger.LogError(stringBuilder.ToString());

                context.HttpContext.Response.Clear();
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Result = new JsonResult(Response<string>.SystemError());
                context.ExceptionHandled = true;
            }
        }
    }
}
